package com.example.baselib.activity

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.viewModelScope
import com.example.baselib.BaseRepository
import com.example.baselib.BaseViewModel
import com.example.baselib.dialog.LoadingDialog
import com.example.baselib.dialog.MsgDialog
import kotlinx.coroutines.*
import java.lang.Exception

/**
 * @author sxygsj.
 * @creat time 2020/4/13 14:05.
 * @description [需要用到viewmode 的网络BaseActivity]
 * @chang time 2020/4/13 14:05.
 * @chang describe []
 */
abstract class BaseViewModelActivity<VM : BaseViewModel> : BaseActivity() {
    protected val loadingDialog by lazy { LoadingDialog(viewModel) }
    protected lateinit var viewModel: VM
    override fun onCreate(savedInstanceState: Bundle?) {
        initVM()
        super.onCreate(savedInstanceState)
        startObserve()
    }


    private fun initVM() {
        providerVMClass()?.let {
            viewModel = ViewModelProviders.of(this).get(it)
            lifecycle.addObserver(viewModel)
        }
        viewModel.setFragmentManager(loadingDialog,supportFragmentManager)
    }

    /**
     * @Description: [绑定viewmodel]
     * @Param:
     * @Return:
     */
    protected abstract fun providerVMClass(): Class<VM>?

    private fun startObserve() {
        //处理一些通用异常，比如网络超时等
        viewModel.run {
            getError().observe(this@BaseViewModelActivity, Observer {
                requestError(it)
            })
            getFinally().observe(this@BaseViewModelActivity, Observer {
                requestFinally(it)
            })
        }
    }

    open fun requestFinally(it: Int?) {
        if (loadingDialog.isVisible)
            loadingDialog.dismiss()

    }

    open fun requestError(it: Exception?) {
        //处理一些已知异常
        it?.run {
            when (it) {
                is TimeoutCancellationException -> {
                    MsgDialog("请求超时,请检查网络").show(
                        supportFragmentManager,
                        "TimeoutCancellationException"
                    )

                }
                is BaseRepository.RequestException -> {
                    MsgDialog(message.toString()).show(
                        supportFragmentManager,
                        "RequestException"
                    )
                }
                is CancellationException -> {
                    MsgDialog("请求取消").show(
                        supportFragmentManager,
                        "RequestException"
                    )
                }

                else -> {
                    MsgDialog(message.toString()).show(
                        supportFragmentManager,
                        "otherException"
                    )
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(viewModel)
    }

}